﻿using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Csla;

namespace Model
{
    [Serializable()]
    public class SoNhanVienBOList : Csla.NameValueListBase<int?, int>
    {
        #region Factory Methods
        private SoNhanVienBOList()
        {
        }

        public void InsertCustomValue(int? customKey, int customValue)
        {
            IsReadOnly = false;
            this.Insert(0, new NameValuePair(customKey, customValue));
            IsReadOnly = true;
        }

        public void CleaAll()
        {
            IsReadOnly = false;
            this.ClearItems();
            IsReadOnly = true;
        }

        private static SoNhanVienBOList _list;

        public static SoNhanVienBOList GetSoNhanVienBOList()
        {
            _list = DataPortal.Fetch<SoNhanVienBOList>(null);
            return _list;
        }

        public static void InvalidateCache()
        {
            _list = null;
        }
        #endregion Factory Methods
        //==========================================================================

        #region Data Access
        protected override void DataPortal_Fetch(object _spParam)
        {
            RaiseListChangedEvents = false;
            SqlDatabase db = new SqlDatabase(Session.DBConnectionString);
            using (SqlDataReader dr = (SqlDataReader)db.ExecuteReader(CommandType.Text, "SELECT PhongBanID,COUNT(NhanVienID) AS [Total] FROM NhanVien GROUP BY PhongBanID"))
            {
                IsReadOnly = false;
                while (dr.Read())
                    this.Add(new NameValuePair((int)dr["PhongBanID"], (int)dr["Total"]));
                IsReadOnly = true;
            }
            RaiseListChangedEvents = true;
        }
        #endregion Data Access
        //==========================================================================
    }
}
